package com.xl.cloud.netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @Author XiangLiang
 * @Since 2025/1/9 14:25
 * @Description: ScatteringAndGatheringTest类<br />
 *
 * NIO还支持通过多个Buffer(即Buffer数组)完成读写操作，即 Scattering 和 Gathering 【举例说明】<br />
 * Scattering:将数据写入到 buffer 时，可以采用 buffer 数组，依次写入   [分散]
 * Gathering:从 buffer 读取数据时，可以采用 buffer 数组，依次读
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7777);

        // 绑定端口到socket并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        // 创建Buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        // 等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        // 假定从客户端接收8个字节的byte数据
        int messageLength = 8;

        // 等待客户端连接(telnet)
        while (true) {
            int byteRead = 0;
            while (byteRead < messageLength) {
                long l = socketChannel.read(byteBuffers);
                byteRead += (int) l;
                System.out.println("byteRead=" + byteRead);

                // 使用流打印，看看当前Buffer的position和limit
                Arrays.stream(byteBuffers)
                        .map(buffer -> "position=" + buffer.position() + ",limit=" + buffer.limit())
                        .forEach(System.out::println);
            }
            // 将所有的Buffer进行flip操作
            Arrays.stream(byteBuffers).forEach(ByteBuffer::flip);
            // 将数据读出显示到客户端
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }
            // 将所有的Buffer进行clear操作
            Arrays.stream(byteBuffers).forEach(ByteBuffer::clear);
            System.out.println("byteRead=" + byteRead + ",byteWrite=" + byteWrite + ",messageLength=" + messageLength);
        }
    }
}
